package com.twu.biblioteca;

import java.util.*;

/**
 * Created by kathy on 17/04/14.
 */

public class CheckoutMovieAction implements Action {

    private Library library;

    private IConsoleReader consoleReader;
    private IConsoleWriter consoleWriter;

    public CheckoutMovieAction(Library library, IConsoleReader consoleReader, IConsoleWriter consoleWriter){
        this.library = library;
        this.consoleReader = consoleReader;
        this.consoleWriter = consoleWriter;
    }

    public void execute(){
        consoleWriter.println("Please input the movie id for checkout: ");
        String id = consoleReader.readInput().toLowerCase().trim();

        while(!checkoutMovie(id) && !id.equals("menu")){
            consoleWriter.println("That movie is not available. Please re-input or enter 'menu' to back to main menu ");
            id = consoleReader.readInput();
        }
        if(!id.equals("menu"))
            consoleWriter.println("Thank you! Enjoy the movie");
    }

    // This method is to check out a movie and returns true if it is successful
    public boolean checkoutMovie(String movieId){

        movieId = movieId.toLowerCase();

        for(Movie aMovie : library.getMovieRepository()){
            if(aMovie.getId().toString().toLowerCase().equals(movieId)
                    && aMovie.getIsAvailable()) {
                aMovie.setIsAvailable(false); // movie is unavailable for others to borrow
                return true;
            }
        }
        return false;
    }
}
